/**
 * 封装 @reach/router，加上根路由前缀
 */

import React from 'react';
import {
  navigate as ReachRouterNavigate,
  Link as ReachRouterLink,
  Router as ReachRouterRouter,
  Location as ReachRouterLocation,
} from '@reach/router';
import { rootPath } from 'utils/constants';

/**
 * 封装 @reach/router 的 Link 组件
 * 用于 spa 跳转（codeup内页面）
 */
export const Link = ({ to, ...others }) => {
  return <ReachRouterLink to={getPathWithRootPath(to)} {...others} />;
};

/**
 * 封装 a 标签
 * 用于整页刷新跳转（codeup内页面）
 */
export const HrefLink = ({ href, ...others }) => {
  return <a href={getPathWithRootPath(href)} {...others}>{others.children}</a>;
};

/** 封装 @reach/router 的 Router */
export const Router = ({ basepath, ...others }) => {
  return <ReachRouterRouter basepath={basepath ? getPathWithRootPath(basepath) : ''} {...others} />;
};

/** 封装 @reach/router 的 Location */
export const Location = ReachRouterLocation;

/**
 * 封装 @reach/router 的 navigate
 * 用于 spa 跳转（codeup内页面）
 */
export const navigate = (to, options) => {
  ReachRouterNavigate(getPathWithRootPath(to), options);
};

/**
 * 封装 window.location.href
 * 用于整页刷新跳转（codeup内页面）
 */
export const navigateHref = (url) => {
  window.location.href = getPathWithRootPath(url);
};


/**
 * 封装 window.open
 * 用于js控制新页面打开
 */
export const navigateOpen = (url, ...args) => {
  return window.open(getPathWithRootPath(url), ...args);
};

/**
 * 给url加上rootPath前缀
 */
export const getPathWithRootPath = (url) => {
  if (!url) {
    return '';
  }

  // 若url已包含域名，则不处理（此情况为读取后端接口返回的完整url）
  if (/^http/.test(url)) {
    return url;
  }

  return `${rootPath}${url}`;
};

/**
 * 给url去掉rootPath前缀
 * 部分场景需要，如调path_info接口时
 */
const prefixReg = new RegExp(`^${rootPath}`);
export const getPathWithNoRootPath = (url) => {
  if (!url) {
    return '';
  }
  if (!prefixReg.test(url)) {
    return url;
  }
  return url.replace(rootPath, '');
};
